/*
 * @Author: WangShuai 1830773767@qq.com
 * @Date: 2025-05-07 21:06:52
 * @LastEditors: WangShuai 1830773767@qq.com
 * @LastEditTime: 2025-05-09 17:15:09
 * @FilePath: \Webgl-basic\src\4.鼠标交互式绘制点.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
    initShader,
} from '../lib/index'
const canvas = document.querySelector('canvas')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
//获取webgl上下文
const gl = canvas.getContext('webgl')
//定义点顶点着色器(字符串)
const vs_shader = /*glsl*/ `
          // 指定浮点数精度为中等精度  
          precision mediump float;//glsl语法每一行后面都要加上分号,每一行后面都要加上分号
          //声明一个属性
          attribute vec4 a_Position;
          attribute vec2 a_Screen_Size;//屏幕大小
          //glsl语法中,必须有一个入口函数main shaderToy里面叫mainImage cesuim里面可能叫czm_Main
          void main(){
            //将a_Position 转化为 屏幕坐标 -1,1 的区间
            vec2 position = a_Position.xy/a_Screen_Size;
            position = position*2.-1.;
            position = position*vec2(1.,-1.);// vec2
            //gl_Position 是最后输出的坐标值,Vec4是四维向量,具有四个分量,每一个分量都是float
            gl_Position=vec4(position,0.0,1.0);
            //gl_PointSize是最后输出点的像素大小  float
            gl_PointSize = 10.0;
          }`
//片元着色器
const fs_shader = /*glsl*/ `
        precision mediump float;
        void main(){
            //gl_FragColor是最后输出的像素颜色,是一个四维的数据
            gl_FragColor = vec4(1.0,0.0,0.0,1.0);            
        }`
//编译着色器,生成程序对象  操作手，专门负责javaScript和shader着色器的通讯
const program = initShader(gl, vs_shader, fs_shader)
//获取到attribute变量的内存地址
const a_Position = gl.getAttribLocation(program, 'a_Position')
const a_Screen_Size = gl.getAttribLocation(program, 'a_Screen_Size')
//设置attribute变量的数据
//第一个参数,attribute变量地址,后面跟着具体要传入的数据
//vertexAttrib4f是一个同族函数 vertexAttrib3f,vertexAttrib2f
gl.vertexAttrib4f(a_Position, 0.5, 0.0, 0.0, 1.0)
gl.vertexAttrib2f(a_Screen_Size, canvas.width, canvas.height);
const points = []
canvas.addEventListener("click", (e) => {
    // canvas.addEventListener("mousemove", (e) => {
    let x = e.pageX;
    let y = e.pageY;
    points.push({
        x,
        y
    })
    renderPoints()
})
const renderPoints = () => {
    //清屏
    gl.clear(gl.COLOR_BUFFER_BIT)
    points.forEach((point) => {
        const {
            x,
            y
        } = point
        gl.vertexAttrib4f(a_Position, x, y, 0.0, 1.0)
        //执行绘制
        gl.drawArrays(gl.POINTS, 0, 1)
    })
}